package cn.taskservice.redis.idempotent.config;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.Collections;

@Slf4j
@Component
public class IdempotentExecutor {

    private static final String LUA_PATH = "script/limit.lua";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ScriptLoader scriptLoader;

    /**
     * 执行幂等校验
     * @param key Redis Key（建议带 hashTag 以支持集群精准路由）
     * @param expireMillis 过期时间（毫秒）
     * @return true 表示幂等成功；false 表示重复请求
     */
    public boolean tryAcquire(String key, long expireMillis) {
        DefaultRedisScript<Long> script = scriptLoader.loadScript(LUA_PATH);
        String requestId = IdUtil.fastSimpleUUID(); // 可作为 future 支持锁释放标识使用

        Long result = stringRedisTemplate.execute(
                script,
                Collections.singletonList(key),
                requestId,
                String.valueOf(expireMillis)
        );

        boolean success = result != null && result == 1;
        if (success) {
            log.info("幂等校验通过: key={}, ttl={}ms", key, expireMillis);
        } else {
            log.warn("幂等校验命中: key={}", key);
        }
        return success;
    }
}
